from trade.models import *
from rest_framework import serializers
from goods.models import *
from goods.serializers import GoodSerializer
import random
import time
from utils.alipay import AliPay
from SxShop3.settings import ali_pub_key_path, private_key_path


# 购物车详情序列化：前端购物车列表需要可跳转到商品详情，
class ShoppingCartDetailSerializer(serializers.ModelSerializer):

    goods = GoodSerializer()

    class Meta:
        model = ShoppingCart
        fields = '__all__'


# 购物车序列化
# Serializer可以更加灵活的处理问题
# ModelSerializer 联合唯一(user, goods)无法通过
# serializer.is_valid(raise_exception=True) 这一步抛异常
class ShoppingCartSerializer(serializers.Serializer):

    # 设置后，添加收藏时是给当前用户添加，而不需要选择用户对象
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    nums = serializers.IntegerField(required=True, min_value=1,
                                    # error_messages={
                                    #     'min_value': '商品数量不能小于一',
                                    #     'required': '请选择购买数量'
                                    # }
                                    )

    goods = serializers.PrimaryKeyRelatedField(required=True,
                                    queryset=Goods.objects.all())

    def create(self, validated_data):
        # 当前用户，request在context上下文中
        user = self.context['request'].user
        nums = validated_data['nums']
        goods = validated_data['goods']

        existed = ShoppingCart.objects.filter(user=user,
                                              goods=goods)
        if existed:
            existed = existed[0]
            existed.nums += nums
            existed.save()
        else:
            existed = ShoppingCart.objects.create(**validated_data)
        return existed

    # Serializer没有重写update方法，需要手动重写
    def update(self, instance, validated_data):
        # 修改商品数量
        instance.nums = validated_data['nums']
        instance.save()
        return instance


# 订单详情
class OrderGoodsSerializer(serializers.ModelSerializer):

    goods = GoodSerializer(many=False)

    class Meta:
        model = OrderGoods
        fields = '__all__'


# 订单序列化2
class OrderDetailSerializer(serializers.ModelSerializer):

    goods = OrderGoodsSerializer(many=True)

    # 新增字段
    alipay_url = serializers.SerializerMethodField(read_only=True)

    # get+字段名
    def get_alipay_url(self, obj):
        alipay = AliPay(
            appid="2016082600314022",
            # 异步处理：网页支付未确认，去手机端支付; 修改订单状态===POST请求
            # 电脑网站支付结果异步通知
            app_notify_url="http://127.0.0.1:8000/alipay/return/",
            app_private_key_path=private_key_path,
            alipay_public_key_path=ali_pub_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://127.0.0.1:8000/alipay/return/"
        )

        url = alipay.direct_pay(
            subject=obj.order_sn,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_mount,
            # 可以不写：data = self.build_body中已经传了self.return_url
            # return_url="http://127.0.0.1:8000/alipay/return/"
        )
        re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)
        print(re_url)
        return re_url

    class Meta:
        model = OrderInfo
        fields = '__all__'


# 订单序列化1
class OrderSerializer(serializers.ModelSerializer):

    # 设置后，添加订单时是给当前用户添加，而不需要选择用户对象
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    # 订单状态和交易号，只能读不能写
    order_sn = serializers.CharField(read_only=True)
    pay_status = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    # 新增字段
    alipay_url = serializers.SerializerMethodField(read_only=True)

    # get+字段名
    # obj就是前端创建的订单
    def get_alipay_url(self, obj):

        # 支付实例
        alipay = AliPay(
            appid="2016082600314022",
            # 异步处理：网页支付未确认，去手机端支付; 修改订单状态===POST请求
            # 电脑网站支付结果异步通知
            app_notify_url="http://127.0.0.1:8000/alipay/return/",
            app_private_key_path=private_key_path,
            alipay_public_key_path=ali_pub_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://127.0.0.1:8000/alipay/return/"
        )
        # 生成参数和签名
        url = alipay.direct_pay(
            subject=obj.order_sn,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_mount,
            # 可以不写：data = self.build_body中已经传了self.return_url
            # return_url="http://127.0.0.1:8000/alipay/return/"
        )
        re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)
        print(re_url)
        return re_url

    def generate_order_sn(self):
        # 当前时间+userid+随机数
        order_sn = str(int(time.time())) + \
                   str(self.context['request'].user.id) + \
                   str(random.randint(10, 99))
        return order_sn

    def validate(self, attrs):
        attrs['order_sn'] = self.generate_order_sn()
        return attrs

    class Meta:
        model = OrderInfo
        fields = '__all__'


